// pages/login/login.js
// 导入用户数据工具
const { validateLogin } = require('../../utils/user.js')

Page({
  data: {
    username: '',
    password: '',
    rememberMe: false
  },

  // 输入用户名
  inputUsername(e) {
    this.setData({
      username: e.detail.value
    })
  },

  // 输入密码
  inputPassword(e) {
    this.setData({
      password: e.detail.value
    })
  },

  // 记住我复选框
  toggleRememberMe() {
    this.setData({
      rememberMe: !this.data.rememberMe
    })
  },

  // 登录
  login() {
    const { username, password, rememberMe } = this.data

    if (!username || !password) {
      wx.showToast({
        title: '请输入用户名和密码',
        icon: 'none'
      })
      return
    }

    // 验证登录
    console.log('登录尝试:', username, password);
    const result = validateLogin(username, password)
    console.log('验证结果:', result);

    if (result.success) {
      // 登录成功
      wx.showLoading({
        title: '登录中...',
      })

      setTimeout(() => {
        wx.hideLoading()

        // 存储用户信息
        const userInfo = result.userInfo
        wx.setStorageSync('userInfo', userInfo)
        wx.setStorageSync('token', 'token_' + Date.now()) // 生成简单的token

        if (rememberMe) {
          wx.setStorageSync('username', username)
          wx.setStorageSync('password', password)
        } else {
          wx.removeStorageSync('username')
          wx.removeStorageSync('password')
        }

        // 根据用户角色跳转到不同页面
        if (userInfo.role === 'admin') {
          wx.navigateTo({
            url: '/pages/admin/admin'
          })
        } else {
          wx.switchTab({
            url: '/pages/index/index'
          })
        }
      }, 500)
    } else {
      // 登录失败
      wx.showToast({
        title: result.message || '用户名或密码错误',
        icon: 'none'
      })
    }
  },

  // 注册
  register() {
    wx.navigateTo({
      url: '/pages/register/register'
    })
  },

  // 忘记密码
  forgetPassword() {
    wx.navigateTo({
      url: '/pages/forgetPassword/forgetPassword'
    })
  },

  onLoad: function () {
    // 检查是否有存储的用户信息
    const username = wx.getStorageSync('username')
    const password = wx.getStorageSync('password')

    if (username && password) {
      this.setData({
        username,
        password,
        rememberMe: true
      })
    }
  }
})